package 类加载器;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project Java_base
 * @create 2019-10-25 22:28
 * @desc 一般来说，loadClass和findClass只要实现一个就可以了
 **/
public class ParentLastClassLoader extends ClassLoader {
    /**
     * 重写loadclass，可以改变双亲优先代理模式
     *
     * @param name
     * @param resolve
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        //通常这一步是必须的
        Class<?> clazz = findLoadedClass(name);
        if (clazz != null) {
            return clazz;
        }
        clazz = findClass(name);
        if (clazz != null) {
            return clazz;
        }
        ClassLoader parent = getParent();
        if (parent != null) {
            return parent.loadClass(name);
        } else {
            return super.loadClass(name, resolve);
        }
    }

    /**
     * 用来封装当前类加载器对象自身的类加载逻辑，一般不想破坏双亲优先代理模式的只需要覆盖它就可以了
     *
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] classData = new byte[0];
        try {
            classData = getClassData(name);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return defineClass(name, classData, 0, classData.length);
    }

    private byte[] getClassData(String name) throws IOException {
        Path classFilePath = Paths.get("/字节码存放的位置");
        return Files.readAllBytes(classFilePath);
    }
}
